package com.woniuxy.commons.rabbbitMQ.provider;

import com.woniuxy.commons.entity.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class DirectProvider {
    @Resource
    private AmqpTemplate amqpTemplate;

    private RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            if(!ack){
                log.info("cause:{}", cause);
                log.info("消息投递失败");
            }else{
                log.info("消息投递成功");
            }
        }
    };

    private RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
            log.warn("消息消费失败!");
            log.warn("message: " + new String(message.getBody()) );
            log.warn(replyText);
            log.warn(Integer.toString(replyCode) );
        }
    };


    //参数：发送的内容
    public void send(Log _log){
        RabbitTemplate template = (RabbitTemplate) amqpTemplate;
        template.setConfirmCallback(confirmCallback);
        template.setReturnCallback(returnCallback);
        //发送消息
        amqpTemplate.convertAndSend("main_exchange","log",_log);
    }
}
